import { IncomingMessage } from "http";
import * as https from "https";

/**
 * 封装 https 请求方法，因为vscode的https请求回来的是一个 https.IncomingMessage 类型的类
 * 需要对请求结果进行处理得到我们想要的数据
 * @param url
 * @returns
 */
const request = async (url: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    https.get(url, (res: IncomingMessage) => {
      let chunks: string = "";
      if (!res || res.statusCode !== 200) {
        reject(new Error("网络请求错误"));
      }
      res.on("data", (chunk) => {
        chunks += chunk.toString("utf-8");
      });
      res.on("end", () => {
        resolve(chunks);
      });
    });
  });
};

/**
 * 根据传入的路径进行网络请求，并生成我们想要的数据格式
 * @param fundData
 * @returns
 */
export function getGzData(fundData: string[]): Promise<FundInfo[]> {
  const time = Date.now();
  const promises: Promise<string>[] = [];

  fundData.forEach((code) => {
    const url = `https://fundgz.1234567.com.cn/js/${code}.js?rt=${time}`;
    promises.push(request(url));
  });
  return Promise.all(promises).then((results) => {
    const resultArr: FundInfo[] = [];
    results.forEach((item) => {
      const match = item.match(/^jsonpgz\((.+)\)/);
      if (!match || !match[1]) {
        return;
      }
      const obj = JSON.parse(match[1]);
      const fundInfo: FundInfo = {
        name: obj.name,
        code: obj.fundcode,
        lastClose: obj.dwjz,
        now: obj.gsz,
        changeRate: obj.gszzl,
        changeAmount: (obj.gsz - obj.dwjz).toFixed(4),
      };
      resultArr.push(fundInfo);
    });
    return resultArr;
  });
}
